package com.accenture.portal.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mv)
			throws Exception {	
		
		//get parameterֵ
		String user_id = request.getParameter("user_id");
		String user_password = request.getParameter("user_password");
		
		//create cookies
		Cookie user_id_cookie = new Cookie ("user_id_cookie", user_id);
		Cookie user_password_cookie = new Cookie ("user_password_cookie", user_password);
		
		//set cookie max age
		user_id_cookie.setMaxAge(10*60);
		user_password_cookie.setMaxAge(10*60);

		//add to cookie
		response.addCookie(user_id_cookie);
		response.addCookie(user_password_cookie);		
	}
	
	/**
	 * if user_id is in right case
	 * @author qinhong.wang
	 * 
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
				
		String user_id = request.getParameter("user_id");
		
		Boolean flag = isNumeric(user_id);
		
		//return true to continue..
		if (flag) {			
			return true;
		} else {
			request.setAttribute("invalidMsg", "user id is invalid, please try agian");
			//forward to login page
			request.getRequestDispatcher("loginView.action").forward(request, response);
			//return false if is be intercepted
			return false;
		}
	}
	
	
	/**
	 * If a String is numberic
	 * @param str
	 * @return 'true' if string is a number, 'false' if not
	 */
	public boolean isNumeric (String str) {
		
		for (int i = 0; i < str.length(); i++) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}

}
